#!/usr/bin/python
# coding=utf8

from database import Storage
import cgi
import json

storage = Storage()
form = cgi.FieldStorage()
res = None

print "Content-Type: application/json\n"

q = form["query"].value if "query" in form else None
if ("table" not in form):
    print ""
elif ("table" in form) and ("limit" in form) and ("offset" in form):
    res = storage.get_table(form["table"].value, long(form["offset"]),
        int(form["limit"].value), q=q)
else:
    res = storage.get_table(form["table"].value, q=q)

if res:
    result = []
    for i in res:
        result.append(storage.todict(i))
    print json.dumps({'main':result})